1 Differences in indicators between academic status groups

1.1 Data preparation

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(here)
## here() starts at /Users/Jo/OneDrive/1_Hertie Studies/Thesis/Hertie-Thesis-Mehler
library(ggplot2)
library(descr)
library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
library(ggpubr)
library(rstatix)
## 
## Attaching package: 'rstatix'
## 
## The following object is masked from 'package:stats':
## 
##     filter
data <- read_csv(here("data/data_combined.csv"))
## Rows: 1019 Columns: 24
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (12): ResponseId, academic_status, educ_cat, gender, age_cat, polinteres...
## dbl (12): age, age10, polinterest, empathy_pc, exp_hate_speech, exp_hostile_...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# filter out NA's in academic status and extreme outliers
data <- data %>% filter(!is.na(educ_cat), !is.na(academic_status), text_length_abs < 1000, readability_score < 40)

indicators <- c("text_length", "readability_score", "leftright_pred_score", "cluster")

1.2 Indicators by Academic Status

p <- ggpairs(data,                 # Data frame
        columns = indicators, # Columns
        aes(color = academic_status,  # Color by group (cat. variable)
            alpha = 0.5),
        upper = list(continuous = wrap("cor", size = 2.7)
        ))

p
## Warning in ggally_statistic(data = data, mapping = mapping, na.rm = na.rm, :
## Removed 664 rows containing missing values

## Warning in ggally_statistic(data = data, mapping = mapping, na.rm = na.rm, :
## Removed 664 rows containing missing values
## Warning: Removed 664 rows containing missing values or values outside the scale range
## (`geom_point()`).
## Removed 664 rows containing missing values or values outside the scale range
## (`geom_point()`).
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_density()`).
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_bin()`).

1.2.1 Example how to extract single plots

getPlot(p, 1, 4)

1.3 Textlength and Academic Status

1.3.1 Mean, SD, T-Test

# logged textlength
data %>%
  group_by(academic_status) %>%
  get_summary_stats(text_length, type = "mean_sd")
## # A tibble: 2 × 5
##   academic_status variable        n  mean    sd
##   <chr>           <fct>       <dbl> <dbl> <dbl>
## 1 academic        text_length   554  6.55  1.29
## 2 non-academic    text_length   385  6.46  1.32
# Base R version
res <- t.test(text_length ~ academic_status, data = data)
res
## 
##  Welch Two Sample t-test
## 
## data:  text_length by academic_status
## t = 1.027, df = 813.87, p-value = 0.3047
## alternative hypothesis: true difference in means between group academic and group non-academic is not equal to 0
## 95 percent confidence interval:
##  -0.08145726  0.26022895
## sample estimates:
##     mean in group academic mean in group non-academic 
##                   6.551834                   6.462449
# statix version
stat.test <- data %>% 
  t_test(text_length ~ academic_status, detailed = TRUE) %>%
  add_significance()
stat.test
## # A tibble: 1 × 16
##   estimate estimate1 estimate2 .y.     group1 group2    n1    n2 statistic     p
##      <dbl>     <dbl>     <dbl> <chr>   <chr>  <chr>  <int> <int>     <dbl> <dbl>
## 1   0.0894      6.55      6.46 text_l… acade… non-a…   554   385      1.03 0.305
## # ℹ 6 more variables: df <dbl>, conf.low <dbl>, conf.high <dbl>, method <chr>,
## #   alternative <chr>, p.signif <chr>
# Create a box-plot
bxp <- ggboxplot(
  data, x = "academic_status", y = "text_length", 
  ylab = "Text Length", xlab = "Groups", add = "jitter"
  )

# Add p-value and significance levels
stat.test <- stat.test %>% add_xy_position(x = "academic_status")
bxp + 
  stat_pvalue_manual(stat.test, tip.length = 0) +
  labs(subtitle = get_test_label(stat.test, detailed = TRUE))

The T-Test shows no significance!

1.4 Readability and Academic Status

1.4.1 T-Test

# t-test
stat.test <- data %>% 
  t_test(readability_score ~ academic_status, detailed = TRUE) %>%
  add_significance()
stat.test
## # A tibble: 1 × 16
##   estimate estimate1 estimate2 .y.   group1 group2    n1    n2 statistic       p
##      <dbl>     <dbl>     <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl>   <dbl>
## 1    0.971      11.9      11.0 read… acade… non-a…   554   385      2.65 0.00819
## # ℹ 6 more variables: df <dbl>, conf.low <dbl>, conf.high <dbl>, method <chr>,
## #   alternative <chr>, p.signif <chr>
# Create a box-plot
bxp <- ggboxplot(
  data, x = "academic_status", y = "readability_score", 
  ylab = "readability_score", xlab = "Groups", add = "jitter"
  )

# Add p-value and significance levels
stat.test <- stat.test %>% add_xy_position(x = "academic_status")
bxp + 
  stat_pvalue_manual(stat.test, tip.length = 0) +
  labs(subtitle = get_test_label(stat.test, detailed = TRUE))

1.5 Cluster Group and Academic Status

crosstab(data$cluster, data$academic_status, prop.c = TRUE)

##    Cell Contents 
## |-------------------------|
## |                   Count | 
## |          Column Percent | 
## |-------------------------|
## 
## ===============================================
##                 data$academic_status
## data$cluster    academic   non-academic   Total
## -----------------------------------------------
## A                   167            109     276 
##                    30.1%          28.3%        
## -----------------------------------------------
## B                   188            116     304 
##                    33.9%          30.1%        
## -----------------------------------------------
## C                    87             87     174 
##                    15.7%          22.6%        
## -----------------------------------------------
## D                   112             73     185 
##                    20.2%          19.0%        
## -----------------------------------------------
## Total               554            385     939 
##                      59%            41%        
## ===============================================
ggplot(data, aes(x = cluster, fill = academic_status)) +
  geom_bar(position = "dodge") +
  labs(title = "Number of Observations per Cluster, Grouped by Academic Status",
       x = "Cluster",
       y = "Number of Observations") +
  theme_minimal()

1.6 Prediction of Political Orientation and Academic Status

1.6.1 T-Test

# t-test
stat.test <- data %>% 
  t_test(leftright_pred_score ~ academic_status, detailed = TRUE) %>%
  add_significance()
stat.test
## # A tibble: 1 × 16
##   estimate estimate1 estimate2 .y.     group1 group2    n1    n2 statistic     p
##      <dbl>     <dbl>     <dbl> <chr>   <chr>  <chr>  <int> <int>     <dbl> <dbl>
## 1    0.226      8.11      7.89 leftri… acade… non-a…   154   121      1.28 0.201
## # ℹ 6 more variables: df <dbl>, conf.low <dbl>, conf.high <dbl>, method <chr>,
## #   alternative <chr>, p.signif <chr>
# Create a box-plot
bxp <- ggboxplot(
  data, x = "academic_status", y = "leftright_pred_score", 
  ylab = "leftright pred score", xlab = "Groups", add = "jitter"
  )

# Add p-value and significance levels
stat.test <- stat.test %>% add_xy_position(x = "academic_status")
bxp + 
  stat_pvalue_manual(stat.test, tip.length = 0) +
  labs(subtitle = get_test_label(stat.test, detailed = TRUE))
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 664 rows containing missing values or values outside the scale range
## (`geom_point()`).

2 Differences in indicators between three edcucation levels

2.1 Indicators by Education Category

p <- ggpairs(data,                 # Data frame
        columns = indicators, # Columns
        aes(color = educ_cat,  # Color by group (cat. variable)
            alpha = 0.5),
        upper = list(continuous = wrap("cor", size = 2.7)
        ))

p
## Warning in ggally_statistic(data = data, mapping = mapping, na.rm = na.rm, :
## Removed 664 rows containing missing values

## Warning in ggally_statistic(data = data, mapping = mapping, na.rm = na.rm, :
## Removed 664 rows containing missing values
## Warning: Removed 664 rows containing missing values or values outside the scale range
## (`geom_point()`).
## Removed 664 rows containing missing values or values outside the scale range
## (`geom_point()`).
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_density()`).
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_bin()`).

2.1.1 Example how to extract single plots

getPlot(p, 1, 4)

2.2 Textlength and Education Cat

# Create the box plot
p <- ggplot(data, aes(x = educ_cat, y = text_length)) +
  geom_point(position = position_jitter(width = 0.2), alpha = 0.5, color = "skyblue") +
  geom_boxplot(outliers = FALSE) +
  theme_minimal() +
  labs(title = "Comparison of Text Length by Education",
       x = "Academic Status",
       y = "Text Length")

# Print the plot
print(p)

2.3 Readability and educ_cat

# Create the box plot
p <- ggplot(data, aes(x = educ_cat, y = readability_score)) +
  geom_point(position = position_jitter(width = 0.2), alpha = 0.5, color = "skyblue") +
  geom_boxplot(outliers = FALSE) +
  theme_minimal() +
  labs(title = "Comparison of Readability by Education",
       x = "Academic Status",
       y = "Readability Score")

# Print the plot
print(p)

2.4 Prediction of Political Orientation and educ_cat

# Create the box plot
p <- ggplot(data, aes(x = educ_cat, y = leftright_pred_score)) +
  geom_point(position = position_jitter(width = 0.2), alpha = 0.5, color = "skyblue") +
  geom_boxplot(outliers = FALSE) +
  theme_minimal() +
  labs(title = "Comparison of Prediction of Political Orientation by educ_cat",
       x = "Education",
       y = "Readability Score")

# Print the plot
print(p)
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 664 rows containing missing values or values outside the scale range
## (`geom_point()`).

3 Density Curves

3.1 Density Curves for Academic Status

# Define the function
plot_density_comparison <- function(data, numeric_var_name, group_var_name = "academic_status") {
  # Ensure the variable names are non-empty and exist in the dataframe
  if (!numeric_var_name %in% names(data)) {
    stop("Numeric variable name does not exist in the dataframe.")
  }
  
  if (!group_var_name %in% names(data)) {
    stop("Group variable name does not exist in the dataframe.")
  }
  
  # Use ggplot to create the density plot
  p <- ggplot(data, aes_string(x = numeric_var_name, fill = group_var_name)) +
    geom_density(alpha = 0.5) + # Adjust alpha for transparency
    labs(x = numeric_var_name, y = "Density") + # Labels
    ggtitle(paste("Density of", numeric_var_name, "by", group_var_name)) +
    scale_fill_manual(values = c("academic" = "skyblue", "non-academic" = "pink")) + # Customize colors
    theme_minimal() # Use a minimal theme for a nicer plot
  
  return(p)
}

# Example usage with your dataframe 'data' and the variable 'readability_score'
plot1 <- plot_density_comparison(data, "text_length")
## Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
## ℹ Please use tidy evaluation idioms with `aes()`.
## ℹ See also `vignette("ggplot2-in-packages")` for more information.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
# For readability_score
plot2 <- plot_density_comparison(data, "readability_score")

# For leftright_pred_score
plot3 <- plot_density_comparison(data, "leftright_pred_score")

# add type/cluster indicator later

plot1

plot2

plot3
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_density()`).

3.2 Density Curves for Education Category

# Define the function
plot_density_comparison <- function(data, numeric_var_name, group_var_name = "educ_cat") {
  # Ensure the variable names are non-empty and exist in the dataframe
  if (!numeric_var_name %in% names(data)) {
    stop("Numeric variable name does not exist in the dataframe.")
  }
  
  if (!group_var_name %in% names(data)) {
    stop("Group variable name does not exist in the dataframe.")
  }
  
  # Use ggplot to create the density plot
  p <- ggplot(data, aes_string(x = numeric_var_name, fill = group_var_name)) +
    geom_density(alpha = 0.5) + # Adjust alpha for transparency
    labs(x = numeric_var_name, y = "Density") + # Labels
    ggtitle(paste("Density of", numeric_var_name, "by", group_var_name)) +
    scale_fill_manual(values = c("High" = "skyblue", "Intermediate" = "lightgreen", "Low" = "pink")) + # Customize colors
    theme_minimal() # Use a minimal theme for a nicer plot
  
  return(p)
}

# Example usage with your dataframe 'data' and the variable 'text_length'
plot5 <- plot_density_comparison(data, "text_length")

# For readability_score
plot6 <- plot_density_comparison(data, "readability_score")

# For leftright_pred_score
plot7 <- plot_density_comparison(data, "leftright_pred_score")

# add type/cluster indicator later

plot5

plot6

plot7
## Warning: Removed 664 rows containing non-finite outside the scale range
## (`stat_density()`).

3.2.1 Facet Wrap of the Plots

DID NOT WORK YET!!

#library(patchwork)
#
## Assuming plot1, plot2, plot3, plot5, plot6, plot7 are your ggplot objects
#plot_layout <- plot1 + plot2 + plot3 + plot5 + plot6 + plot7 +
#  plot_layout(guides = "collect") &
#  theme(legend.position = "bottom")
#
#plot_layout <- plot1 + plot2 + plot3 + plot5 + plot6 + plot7 +
#  plot_layout(ncol = 2) # This is the correct usage to specify layout options
#
#
#plot_layout